package cn.touna.jss.modules.custom.carmodel.synctask;

import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.carmodel.entity.Car300BrandEntity;
import cn.touna.jss.modules.custom.carmodel.entity.Car300ModelEntity;
import cn.touna.jss.modules.custom.carmodel.entity.Car300SeriesEntity;
import cn.touna.jss.modules.custom.carmodel.mapper.Car300BrandEntityMapper;
import cn.touna.jss.modules.custom.carmodel.mapper.Car300ModelEntityMapper;
import cn.touna.jss.modules.custom.carmodel.mapper.Car300SeriesEntityMapper;
import cn.touna.jss.modules.third.car300.Car300Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * Created by Steve.Tao on 2017/11/20.
 */
@Lazy
@Service
public class Car300SyncModelService extends AbstractSyncModelService {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private Car300Service car300Service;

    @Autowired
    private Car300BrandEntityMapper car300BrandEntityMapper;

    @Autowired
    private Car300SeriesEntityMapper car300SeriesEntityMapper;

    @Autowired
    private Car300ModelEntityMapper car300ModelEntityMapper;

    public SyncModelResult refreshModel(String taskNo) {
        LocalDateTime startTime = LocalDateTime.now();
        SyncModelResult result = new SyncModelResult();
        result.setBeginTime(startTime.toString());
        logger.info("【同步车型】车300车型同步任务开始，taskNo:{} @ time:{} ", taskNo, startTime.toString());
        Counter counter = new Counter();
        try {
            String brandResStr = car300Service.getCarBrandList();
            if (StringUtils.isBlank(brandResStr))
                return fail(result, "获取车300品牌失败，结果为空");


            JSONObject brandResObj = JSONObject.parseObject(brandResStr);
            if (brandResObj.getInteger("status") == 0) {
                logger.info("【同步车型】获取车300品牌失败");
                return fail(result, "获取车300品牌失败,状态为失败");
            }
            JSONArray brandArray = brandResObj.getJSONArray("brand_list");
            if (brandArray == null || brandArray.size() == 0)
                return null;
            //更新入库
            for (int i = 0; i < brandArray.size(); i++) {
                Car300BrandEntity brandEntity = parseBrand(brandArray.getJSONObject(i));
                if (brandEntity == null) {
                    counter.count("brand.null");
                    continue;
                }

                int insertBrandCount = car300BrandEntityMapper.insert(brandEntity);
                if (insertBrandCount == 0) {
                    car300BrandEntityMapper.updateByBrandId(brandEntity);
                    counter.count("brand.update");
                } else {
                    counter.count("brand.insert");
                }
                refreshSeries(taskNo, brandEntity.getBrandId(), counter);
            }
            result.setSuccess();
            return result;
        } catch (Exception e) {
            logger.info("【同步车型】同步车系返回错误，taskNo:{},message:{}", taskNo, e.getMessage());
        } finally {
            if (result.isSuccess()) {
                result.setMessage(counterToMessage(counter));
            }
            LocalDateTime stopTime = LocalDateTime.now();
            Duration duration = Duration.between(stopTime, startTime);
            result.setEndTime(stopTime.toString());
            result.setCost(duration.toString());
            logger.info("【同步车型】车300车型同步任务完成，taskNo:{} cost:{}ms @ time:{} ", taskNo, duration.toString(), stopTime.toString());
        }
        return fail(result, counterToMessage(counter));
    }

    private SyncModelResult fail(SyncModelResult result, String message) {
        result.setFailed();
        result.setMessage(message);
        return result;
    }

    private void refreshSeries(String taskNo, int brandId, Counter counter) {
        try {
            String res = car300Service.getCarSeriesList(String.valueOf(brandId));
            if (StringUtils.isBlank(res))
                return;
            JSONObject resObj = JSONObject.parseObject(res);
            if (resObj.getInteger("status") == 0)
                return;
            JSONArray seriesArray = resObj.getJSONArray("series_list");
            for (int i = 0; i < seriesArray.size(); i++) {
                Car300SeriesEntity entity = parseSeries(taskNo, brandId, seriesArray.getJSONObject(i));
                if (entity == null) {
                    counter.count("series.null");
                    continue;
                }
                int insertCount = car300SeriesEntityMapper.insert(entity);
                if (insertCount == 0) {
                    car300SeriesEntityMapper.updateBySeriesId(entity);
                    counter.count("series.update");
                } else {
                    counter.count("series.insert");
                }
                refreshModel(taskNo, brandId, entity.getSeriesId(), counter);
            }
        } catch (Exception e) {
            counter.count("series.exception");
            logger.error("【同步车型】同步车300车系异常，taskNo：{},brandId:{},message:{}", taskNo, brandId, e.getMessage());
        }
    }

    private void refreshModel(String taskNo, int brandId, int seriesId, Counter counter) {
        int fuelType = 0;
        try {
            String res = car300Service.getCarModelList(String.valueOf(seriesId));
            if (StringUtils.isBlank(res))
                return;
            JSONObject resObj = JSONObject.parseObject(res);
            if (resObj.getInteger("status") == 0)
                return;
            JSONArray modelArray = resObj.getJSONArray("model_list");
            for (int i = 0; i < modelArray.size(); i++) {
                Car300ModelEntity entity = parseModel(taskNo, brandId, seriesId, modelArray.getJSONObject(i));
                if (entity == null) {
                    counter.count("model.null");
                    continue;
                }
                fuelType = entity.getFuelType();
                int insertCount = car300ModelEntityMapper.insert(entity);
                if (insertCount == 0) {
                    car300ModelEntityMapper.updateByModelId(entity);
                    counter.count("model.update");
                } else {
                    counter.count("model.insert");
                }
            }
        } catch (Exception e) {
            counter.count("model.exception");
            System.out.println("fuelType:" + fuelType);
            logger.error("【同步车型】同步车300车模异常，taskNo：{},brandId:{},seriesId:{},message:{}", taskNo, brandId, seriesId, e.getMessage());
        }
    }

    private Car300ModelEntity parseModel(String taskNo, int brandId, int seriesId, JSONObject obj) {
        try {
            Car300ModelEntity entity = new Car300ModelEntity();
            entity.setCreateUser("SYNC_USER");
            entity.setUpdateUser("SYNC_USER");
            entity.setSeriesId(seriesId);
            entity.setUpdateTime(getDate(obj.getString("update_time")));
            entity.setModelId(Integer.valueOf(obj.getString("model_id")));
            entity.setModelName(obj.getString("model_name"));
            entity.setModelPrice(getBigDeicimal(getString(obj, "model_price")));
            entity.setModelYear(getString(obj, "model_year"));
            entity.setDischargeStandard(getString(obj, "discharge_standard"));
            entity.setGearType(getString(obj, "gear_type"));
            entity.setLiter(getString(obj, "liter"));
            entity.setMaxRegYear(getString(obj, "max_reg_year"));
            entity.setMinRegYear(getString(obj, "min_reg_year"));
            entity.setSeatNumber(getString(obj, "seat_number"));
            entity.setFuelType(obj.getInteger("fuel_type"));
            return entity;
        } catch (Exception e) {
            logger.error("Car300ModelEntity，taskNo:{},brandId:{},seriesId:{},json:{},message:{}", taskNo,
                    brandId, seriesId, obj, e.getMessage());
        }
        return null;
    }

    private Car300SeriesEntity parseSeries(String taskNo, int brandId, JSONObject obj) {
        try {
            Car300SeriesEntity entity = new Car300SeriesEntity();
            entity.setSeriesId(Integer.valueOf(obj.getString("series_id")));
            entity.setSeriesName(obj.getString("series_name"));
            entity.setSeriesGroupName(obj.getString("series_group_name"));
            entity.setUpdateTime(getDate(obj.getString("update_time")));
            entity.setLevelName(getString(obj, "series_level"));
            entity.setMakerType(getString(obj, "maker_type"));
            entity.setBrandId(brandId);
            entity.setCreateUser("SYNC_USER");
            entity.setUpdateUser("SYNC_USER");
            return entity;
        } catch (Exception e) {
            logger.error("jsonobject转Car300SeriesEntity异常，taskNo:{},brandId:{},json:{},message:{}", taskNo,
                    brandId, obj.toJSONString(), e.getMessage());
        }
        return null;
    }

    private Car300BrandEntity parseBrand(JSONObject obj) {
        try {
            Car300BrandEntity entity = new Car300BrandEntity();
            entity.setBrandId(Integer.valueOf(obj.getString("brand_id")));
            entity.setBrandName(obj.getString("brand_name"));
            entity.setInitial(obj.getString("initial"));
            entity.setCreateUser(SYNC_USER);
            entity.setUpdateUser(SYNC_USER);
            //ldt.atZone(ZoneId.systemDefault()).toInstant()
            entity.setUpdateTime(getDate(obj.getString("update_time")));
            return entity;
        } catch (Exception e) {
            logger.error("jsonobject转Car300BrandEntity失败，", e);
        }
        return null;
    }


}
